package common

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/gogf/gf/util/gconv"
	"math"
	"mdblog/models/analysis"
	"mdblog/models/blog"
	"strings"
	"time"
)

func init() {
	_ = beego.AddFuncMap("tsc", TimeStampConversion)                     //将时间戳转成正常时间
	_ = beego.AddFuncMap("makeLabels", ArticleLabelsHtml)                //将时间戳转成正常时间
	_ = beego.AddFuncMap("ClassifyName", ClassifyName)                   //将时间戳转成正常时间
	_ = beego.AddFuncMap("articleAuthor", ArticleCreateBy)               // 获取文章作者
	_ = beego.AddFuncMap("visitCount", analysis.GetToDayVisitCount)      // 今日访问数
	_ = beego.AddFuncMap("articleCount", blog.ArticlesCount)             // 文章数量
	_ = beego.AddFuncMap("resourceCount", blog.ResourceCount)            // 资源数量
	_ = beego.AddFuncMap("resourceAllSize", blog.ResourceSizeTotal)      // 资源总大小
	_ = beego.AddFuncMap("HumanReadByte", HumanReadByte)                 // 资源总大小
	_ = beego.AddFuncMap("AllEnableCarousel", blog.GetAllEnableCarousel) // 所有轮播图
}

func TimeStampConversion(timestamp time.Time, exact bool) string {
	if exact == false {
		return timestamp.Format("2006-01-02")
	} else {
		return timestamp.Format("2006-01-02 15:04:05")
	}
}

func ClassifyName(id int) string {
	class, err := blog.GetBlogClassify(id)
	if err != nil {
		return "未知"
	}
	return class.Name
}

func HumanReadByte(num int64) string {
	num1 := gconv.Float64(num)
	if num == 0 {
		return "0 b"
	}
	var (
		size  = 1024
		i     = 0
		units = []string{"b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"}
	)
	for index, _ := range units {
		result := num1 / math.Pow(float64(size), float64(index+1))
		if result < 1 {
			break
		}
		i = index + 1
	}
	return fmt.Sprintf("%.2f %s", num1/math.Pow(float64(size), float64(i)), units[i])
}

func ArticleLabelsHtml(labels string) string {
	html := ""
	targets, _ := blog.GetAllArticleTargets()
	for _, label := range strings.Split(labels, ",") {
		for _, target := range targets {
			if target.Id == gconv.Int(label) {
				html += fmt.Sprintf(`<a href="javascript:;">%s</a>`, target.Name)
			}
		}
	}
	return html
}

func ArticleCreateBy(author, def string) string {
	if author == "" && def == "" {
		return "默认作者"
	} else if author != "" {
		return author
	} else if author == "" && def != "" {
		return def
	}
	return def
}
